<template>
  <el-dialog v-model="visible" title="编辑规则信息" width="450px" :close-on-click-modal="false" @closed="handleClosed">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" :disabled="loading">
      <el-row>
        <el-form-item label="规则名称" prop="name" label-width="80px">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="产品" label-width="80px" prop="product_id">
          <el-select-v2 v-model="form.product_id" filterable :options="selectProductList" placeholder="请选择适用的产品"
            style="width: 100%" clearable :props="{
              value: 'product_id',
              label: 'product_name'
            }" >

            <template #default="{ item }">
              <el-tooltip
                  effect="dark"
                  :content="item.product_name"
                  placement="right"
                  :open-delay="500"
                  :hide-after="0"
              >
                <span class="truncate">{{ item.product_name }}</span>
              </el-tooltip>
            </template>

          </el-select-v2>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="渠道" label-width="80px" prop="channel_id">
          <el-select-v2 v-model="form.channel_id" filterable :options="selectChannelList" placeholder="请选择适用的渠道"
            style="width: 100%" clearable :props="{
              value: 'channel_id',
              label: 'channel_name'
            }" >

            <template #default="{ item }">
              <el-tooltip
                  effect="dark"
                  :content="item.channel_name"
                  placement="right"
                  :open-delay="500"
                  :hide-after="0"
              >
                <span class="truncate">{{ item.channel_name }}</span>
              </el-tooltip>
            </template>

          </el-select-v2>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="客户" label-width="80px" prop="customer_id">
          <el-select-v2 v-model="form.customer_id" filterable :options="selectCustomerList" placeholder="请选择适用的客户"
            style="width: 100%" clearable :props="{
              value: 'customer_id',
              label: 'customer_shortname'
            }" >
            <template #default="{ item }">
              <el-tooltip
                  effect="dark"
                  :content="item.customer_shortname"
                  placement="right"
                  :open-delay="500"
                  :hide-after="0"
              >
                <span class="truncate">{{ item.customer_shortname }}</span>
              </el-tooltip>
            </template>

          </el-select-v2>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="服务商" label-width="80px" prop="cos_server_type">
          <el-select-v2 v-model="form.cos_server_type" filterable :options="cosServerList" placeholder="请选择推送的COS服务商"
            style="width: 100%" clearable :props="{
              value: 'code',
              label: 'desc'
            }" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="打印类型" label-width="80px" prop="print_type">
          <el-select-v2 v-model="form.print_type" filterable :options="printTypeList" placeholder="请选择查询的打印类型"
            style="width: 100%" clearable :props="{
              value: 'code',
              label: 'desc'
            }" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="开始时间" label-width="80px" prop="label_push_start_date">
          <el-date-picker v-model="form.label_push_start_date" type="datetime" placeholder="请选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </el-row>


    </el-form>

    <template #footer>
      <el-button @click="close" :disabled="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useDictStore } from '@/store/dictStore'

//定义产品下拉框
let selectProductList = ref([])
//渠道下拉框
let selectChannelList = ref([])
//客户下拉框
let selectCustomerList = ref([])

let printTypeList = ref([])
let printConfigStatuList = ref([])
let cosServerList = ref([])

const dictStore = useDictStore()

onMounted(async () => {
  requestIdleCallback(async () => {
    selectProductList.value = await dictStore.loadDict('product')
  })

  requestIdleCallback(async () => {
    selectChannelList.value = await dictStore.loadDict('channel')
  })

  requestIdleCallback(async () => {
    selectCustomerList.value = await dictStore.loadDict('customer')
  })

  requestIdleCallback(async () => {
    printTypeList.value = await dictStore.loadDict('getAllPrintType')
  })

  requestIdleCallback(async () => {
    printConfigStatuList.value = await dictStore.loadDict('getAllPrintConfigStatus')
  })

  requestIdleCallback(async () => {
    cosServerList.value = await dictStore.loadDict('getAllCosServer')
  })
})


const props = defineProps({
  modelValue: Boolean,
  recordKey: [String, Number],
  getDetail: Function,
  onSubmit: Function,
  excSuccess: Function,
})

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'submit', data: {}): void
}>()

const visible = ref(props.modelValue)
const loading = ref(false)

watch(() => props.modelValue, val => (visible.value = val))

watch(visible, async (val) => {
  emit('update:modelValue', val)

  if (val) {
    form.value = { ...defaultForm }
    nextTick(() => formRef.value?.resetFields())

    // 如果是编辑模式，获取详情
    if (props.recordKey != null && props.getDetail) {
      loading.value = true
      try {
        const detail = await props.getDetail(props.recordKey)
        console.log(detail)
        if (detail) {
          form.value = { ...form.value, ...detail }
        } else {
          ElMessage.warning('未获取到有效的详情数据')
        }
      } catch (err: any) {
        console.error(err)
        ElMessage.error('获取详情失败，请稍后重试')
        // 弹窗打开失败可以自动关闭
        visible.value = false
      } finally {
        loading.value = false
      }
    }
  }
})

const formRef = ref()

const defaultForm = {
  id: '',
  name: '',
  product_id: '',
  channel_id: '',
  customer_id: '',
  print_type: '',
  status: '',
  label_push_start_date: '',
  cos_server_type: ''
}

const form = ref({ ...defaultForm })

// const atLeastOneSelect = (rule: any, value: any, callback: any) => {
//   const { channel_id, product_id, customer_id } = form.value
//   if (!channel_id && !product_id && !customer_id) {
//     callback(new Error('请在产品、渠道和客户中至少选择一个选项'))
//   } else {
//     callback()
//   }
// }


const createStartDateValidator = (maxDays: number) => {
  return (rule: any, value: string, callback: any) => {
    console.log(value)
    if (!value) {
      return callback(new Error('请选择开始时间'))
    }

    const selectedDate = new Date(value)
    const now = new Date()
    const diffDays = (now.getTime() - selectedDate.getTime()) / (1000 * 60 * 60 * 24)

    if (diffDays > maxDays) {
      return callback(new Error(`开始时间不能早于当前时间的 ${maxDays} 天之前`))
    }

    callback()
  }
}

const rules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  cos_server_type: [{ required: true, message: '请选择服务商', trigger: 'change' }],
  print_type: [{ required: true, message: '请选择打印类型', trigger: 'change' }],
  label_push_start_date: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change'  // 推荐用 change 而非 blur，因为日期选择器更适合 change 触发
    },
    { validator: createStartDateValidator(45), trigger: 'change' }
  ]
  //   channel_id: [{ validator: atLeastOneSelect, trigger: 'change' }],
  //   product_id: [{ validator: atLeastOneSelect, trigger: 'change' }],
  //   customer_id: [{ validator: atLeastOneSelect, trigger: 'change' }],
}

const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {

      const { channel_id, product_id, customer_id } = form.value
      if (!channel_id && !product_id && !customer_id) {
        ElMessage.error('请至少选择一个渠道 / 产品 / 客户')
        return
      }



      try {
        props.onSubmit(form.value)
          .then(data => {

            console.log(data)
            if (props.excSuccess) {
              props.excSuccess();  // 例如：刷新表格数据
            }


            close()
          })
      } catch (err) {
        console.log(err)
        if (err === false) {
          ElMessage.error('请完善表单信息')
        } else {
          console.error('提交异常', err)
          ElMessage.error('提交异常，请稍后重试')
        }
      }

    } else {
      ElMessage.error('请完善表单信息')
    }
  })
}

const close = () => {
  visible.value = false
}

const handleClosed = () => {
  nextTick(() => {
    formRef.value?.resetFields()
    form.value = { ...defaultForm }
  })
}
</script>

<style scoped>
.truncate {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
